﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Security;

namespace Networking
{
    /// <summary>
    /// Packet of type PacketAutenticationResponse, the response packet in autentication process which contains the encoded challenge bytes
    /// </summary>
    public class AutenticationResponsePacket : Packet
    {

        /// <summary>
        /// The challenge bytes
        /// </summary>
        private byte[] _Challenge;

        /// <summary>
        /// A copy of the challenge bytes used in autentication process
        /// </summary>
        public byte[] Challenge
        {
            get
            {
                return (byte[])_Challenge.Clone();
            }
        }

        /// <summary>
        /// Check if challenge
        /// </summary>
        /// <param name="iChallenge"></param>
        /// <returns></returns>
        public bool CheckChallenge(int iChallenge)
        {
            byte[] temp = MD5.Create().ComputeHash(BitConverter.GetBytes(iChallenge));

            for (int n = 0; n < temp.Length; n++)
            {
                if (temp[n] != _Challenge[n]) return false;
            }

            return true;
        }

        /// <summary>
        /// Creates a new instance of PacketAutenticationResponse with the provided challenge
        /// </summary>
        /// <param name="Challenge">The challenge bytes</param>
        public AutenticationResponsePacket(int iChallenge)
            : base(PacketType.AutenticationResponse)
        {

            _Challenge = MD5.Create().ComputeHash(BitConverter.GetBytes(iChallenge));

            //_Challenge = BitConverter.GetBytes(iChallenge);

        }

        /// <summary>
        /// Creates a new instance of AutenticationResponsePacket extracting all the parameters from the byte buffer
        /// </summary>
        /// <param name="buffer">The byte buffer containing the packet data</param>
        public AutenticationResponsePacket(byte[] buffer)
            : base(PacketType.AutenticationResponse, buffer)
        {
            //
        }

        /// <summary>
        /// Serializes the packet in order to send it
        /// </summary>
        /// <returns>The bytes of the packet</returns>
        public override byte[] Serialize()
        {

            return (byte[])_Challenge.Clone();
            
        }

        /// <summary>
        /// Loads a packet from a byte buffer
        /// </summary>
        /// <param name="buffer">The data buffer</param>
        public override void Load(byte[] buffer)
        {
            if (buffer.Length != 16) throw new BufferSizeMismatchException(16);

            _Challenge = new byte[16];

            buffer.CopyTo(_Challenge, 0);
        }
    }

}
